#!/usr/bin/env python
# -*- coding: utf-8 -*-
# --------------------------------------
# Author:  LJ
# Email:   admin@attacker.club

# Last Modified: 2018-06-19 21:06:54
# Description: py3
# --------------------------------------
import paramiko
import time
import pprint
import socket
import re

DEBUG = True  # False 读取host.txt列表主机


user = 'root'
passwd = input('输入密码: ')

hostlist = [
    'account-98-1',
    'account-98-10',
]



def run(host):
    date = time.strftime("%b %d %H:%M:%S", time.localtime())
    print("INFO:\t%s\t[\033[1;32m%s\033[0m] Trying to connect　..." % (date, host))
    paramiko.util.log_to_file('paramiko.log')

    ssh = paramiko.SSHClient()
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    count = 0
    try:
        ssh.connect(
            hostname=host,
            username=user,
            password=passwd,
            port=22,
            pkey=None, look_for_keys=False,
            timeout=3, allow_agent=False)

        for cmdline in cmdlist:
            count += 1
            stdin, stdout, stderr = ssh.exec_command(cmdline)
            print("INFO:\t%s\t\033[1;34m[%s]\033[0m\t%s" %
                  (date, count, cmdline))
        results['successful'].append(host)

    except (paramiko.ssh_exception.AuthenticationException,) as e:
        print("INFO:\t%s\t\033[1;31mLogin failed\033[0m\t%s" % (date, e))
        results['unsuccessful'].append(host)
    except (paramiko.ssh_exception.NoValidConnectionsError, socket.gaierror, socket.timeout, socket.error) as e:
        print("INFO:\t%s\t\033[1;31mConnection failed\033[0m\t%s" % (date, e))
        results['unsuccessful'].append(host)
    except Exception as e:
        print(e, type(e))
    finally:
        ssh.close()


if __name__ == '__main__':
  
    cmdlist = [
    "ls /root",
    "touch /tmp/paramiko.py"
    ]


    results = {
        'unsuccessful': [],
        'successful': [],
    }

    if not DEBUG:
        with open("host.txt") as f:
            for host in f:

                result = re.match(r'(\w+)\-(.*)', host).groups()
                result = (list(result))  # 主机名和编号，将元组结果转列表
                result.reverse()  # 反转列表    account-98-1 -> 98-1.account
                domain = '.'.join(result)  # 拼接

                run(domain)

    else:
        print("DEBUG:\tTest")
        for host in hostlist:

            result = re.match(r'(\w+)\-(.*)', host).groups()
            result = (list(result))  # 主机名和编号，将元组结果转列表
            result.reverse()  # 反转列表
            domain = '.'.join(result)  # 拼接

            run(domain)

    pprint.pprint(results)




